<?php

namespace App\Logic;

use App\Model\Article;
use App\Model\ArticleAuthor;
use App\Model\ArticleContent;
use App\Model\Category;
use Exception;
use function Hyperf\Support\env;

class AdminArticleLogic
{
    /**
     * 资讯列表
     * @param $input
     * @return array
     */
    public static function listArticle($input): array
    {
        [$pageNum, $pageSize, $offset] = parsePageParams($input);
        $query = Article::query()->when(!empty($input['query']['catid']), function ($query) use ($input) {
            $query->where('catid', (int)$input['query']['catid']);
        })->when(!empty($input['query']['keyword']), function ($query) use ($input) {
            $query->where('title', 'like', "%{$input['query']['keyword']}%");
        });
        $total = $query->count();
        if ($total) {
            $records = $query->with(['category'])->orderBy('id', 'desc')->offset($offset)->limit($pageSize)->get()->toArray();
            if (!empty($input['query']['keyword']) && !empty($records)) {
                array_walk($records, function (&$v) use ($input) {
                    $v['highlight_title'] = str_replace($input['query']['keyword'], '<span style="color:red">' . $input['query']['keyword'] . '</span>', $v['title']);
                });
            }
        }
        return [
            'total' => $total,
            'pages' => ceil($total / $pageSize),
            'records' => $records ?? []
        ];
    }

    /**
     * 文章详情
     * @param $id
     * @return array
     */
    public static function detailArticle($id): array
    {
        $article = Article::query()->where('id', $id)->with(['content', 'author'])->first()->toArray();
        $article['thumb_url'] = img_url($article['thumb']);
        $article['content'] = $article['content']['content'];
        return $article;
    }

    /**
     * 添加资讯
     * @param $input
     * @return false|array
     */
    public static function addArticle($input): false|array
    {
        $imageList = self::_parseContentImage($input['content']);
        $author = self::getAuthor($input['author']);
        $article = Article::create([
            'catid' => $input['catid'],
            'title' => $input['title'],
            'thumb' => empty($input['thumb']) && !empty($imageList) ? $imageList[0] : $input['thumb'],
            'image_list' => new_json_encode($imageList),
            'keywords' => $input['keywords'],
            'description' => $input['description'] ?? '',
            'is_recommend' => isset($input['isRecommend']) ? 1 : 0,
            'source' => 1,
            'author_id' => $author['id'],
            'add_time' => time(),
            'edit_time' => time(),
        ]);
        if ($article) {
            ArticleContent::create([
                'contentid' => $article['id'],
                'content' => $input['content']
            ]);
            return $article->toArray();
        }
        return false;
    }

    /**
     * 修改文章
     * @param $id
     * @param $input
     * @return bool
     */
    public static function editArticle($id, $input): bool
    {
        $imageList = self::_parseContentImage($input['content']);
        $author = self::getAuthor($input['author']);
        $rt = Article::query()->where('id', $id)->update([
            'catid' => $input['catid'],
            'title' => $input['title'],
            'thumb' => empty($input['thumb']) && !empty($imageList) ? $imageList[0] : $input['thumb'],
            'image_list' => new_json_encode($imageList),
            'keywords' => $input['keywords'],
            'is_recommend' => isset($input['isRecommend']) ? 1 : 0,
            'author_id' => $author['id'],
            'edit_time' => time(),
        ]);
        if ($rt) {
            ArticleContent::where('contentid', $id)->update([
                'content' => $input['content']
            ]);
            return true;
        }
        return false;
    }

    /**
     * 删除文章
     * @param $id
     * @return true
     */
    public static function delArticle($id): true
    {
        $ids = explode(',', trim($id));
        Article::whereIn('id', $ids)->delete();
        ArticleContent::whereIn('contentid', $ids)->delete();
        return true;
    }

    /**
     * 推荐/取消推荐
     * @param $id
     * @param $isUnRecommend
     * @return true
     */
    public static function recommend($id, $isUnRecommend = false): true
    {
        $ids = explode(',', trim($id));
        Article::query()->whereIn('id', $ids)->update(['is_recommend' => $isUnRecommend ? 0 : 1]);
        return true;
    }

    /**
     * 获取分类列表
     * @param bool $keyBy
     * @return array
     */
    public static function listCategory($keyBy = false): array
    {
        $data = Category::query()->orderBy('listorder', 'asc')->orderBy('id', 'asc')->get();
        if ($keyBy) {
            $data = $data->keyBy('id');
        }
        return [
            'total' => Category::query()->count(),
            'pages' => 1,
            'records' => $data->toArray()
        ];
    }

    /**
     * 添加栏目
     * @param $input
     * @return bool
     * @throws Exception
     */
    public static function addCategory($input): bool
    {
        $cat = Category::query()->where('catname', $input['catname'])->first();
        if ($cat) {
            throw new  Exception('分类已存在');
        }
        $category = Category::create([
            'game_id' => $input['gameId'] ?? 0,
            'sport_id' => $input['sportId'] ?? 0,
            'parentid' => $input['parentid'] ?? 0,
            'catname' => $input['catname'],
            'catdir' => $input['catdir'] ?? '',
            'letter' => '',
            'parentdir' => $input['parentdir'] ?? '',
            'keywords' => $input['keywords'] ?? '',
            'description' => $input['description'] ?? '',
            'arrparentid' => $input['arrparentid'] ?? '',
            'arrchildid' => $input['arrchildid'] ?? '',
            'child' => 0,
            'url' => '',
            'listorder' => $input['listorder'] ?? 0,
            'add_time' => time()
        ]);
        return $category->id > 0;
    }

    /**
     * 修改分类
     * @param $catId
     * @param $input
     * @return true
     * @throws Exception
     */
    public static function editCategory($catId, $input): true
    {
        if (Category::query()->where('id', '<>', $catId)->where('catname', $input['catname'])->exists()) {
            throw new Exception('分类名称重复');
        }
        Category::query()->where('id', $catId)->update([
            'catname' => $input['catname'],
            'listorder' => $input['listorder']
        ]);
        return true;
    }

    /**
     * 删除分类
     * @param $catId
     * @return true
     * @throws Exception
     */
    public static function delCategory($catId): true
    {
        if (Article::query()->where('catid', $catId)->exists()) {
            throw new Exception('该栏目下包含资讯不可删除');
        }
        Category::query()->where('id', $catId)->delete();
        return true;
    }

    /**
     * 分类详情
     * @param $catId
     * @return array
     * @throws Exception
     */
    public static function detailCategory($catId): array
    {
        $category = Category::query()->where('id', $catId)->first();
        if (!$category) {
            throw new Exception('该栏目不存在');
        }
        return $category->toArray();
    }

    /**
     * 修改分类字段
     * @param $catId
     * @param $field
     * @param $value
     * @return true
     * @throws Exception
     */
    public static function updateCategoryField($catId, $field, $value): true
    {
        if (!in_array($field, ['listorder'])) {
            throw new Exception('不支持修改该值');
        }
        Category::query()->where('id', $catId)->update([$field => $value]);
        return true;
    }

    /**
     * 作者列表
     * @param $input
     * @return array
     */
    public static function listAuthor($input): array
    {
        [$pageNum, $pageSize, $offset] = parsePageParams($input);
        $total = ArticleAuthor::count();
        if ($total) {
            $records = ArticleAuthor::query()->orderBy('id', 'desc')->limit($pageSize)->offset($offset)->get()->toArray();
        }
        return [
            'total' => $total,
            'pages' => ceil($total / $pageSize),
            'records' => $records ?? []
        ];
    }

    /**
     * 添加作者
     * @param $input
     * @return array
     * @throws Exception
     */
    public static function addAuthor($input): array
    {
        if (ArticleAuthor::query()->where('name', $input['name'])->exists()) {
            throw new Exception('该作者已存在');
        }
        $author = ArticleAuthor::create([
            'name' => $input['name'],
            'avatar' => $input['avatar'],
        ]);
        if (!$author) {
            throw new Exception('添加失败');
        }
        return $author->toArray();
    }

    /**
     * 修改作者信息
     * @throws Exception
     */
    public static function editAuthor($id, $input): true
    {
        if (ArticleAuthor::query()->where('id', '<>', $id)->where('name', $input['name'])->exists()) {
            throw new Exception('该作者名称已存在');
        }
        $author = ArticleAuthor::query()->where('id', $id)->first();
        if (!$author) {
            throw new Exception('该作者不存在');
        }
        $ret = ArticleAuthor::query()->where('id', $id)->update([
            'name' => $input['name'],
            'avatar' => $input['avatar'],
            'total_hits' => $input['total_hits'] ?? $author['total_hits'],
        ]);
        if (!$ret) {
            throw new Exception('修改失败');
        }
        return true;
    }

    /**
     * 删除作者
     * @param $id
     * @return true
     * @throws Exception
     */
    public static function delAuthor($id): true
    {
        if (Article::query()->where('author_id', $id)->exists()) {
            throw new Exception('该作者尚有文章，不可删除');
        }
        if (!ArticleAuthor::query()->where('id', $id)->delete()) {
            throw new Exception('删除失败');
        }
        return true;
    }

    /**
     * 获取作者
     * @param $authorName
     * @param string $authorAvatar
     * @return array
     */
    public static function getAuthor($authorName, $authorAvatar = ''): array
    {
        $author = ArticleAuthor::query()->where('name', $authorName)->first();
        if ($author) {
            return $author->toArray();
        }
        $author = ArticleAuthor::create([
            'name' => $authorName,
            'avatar' => $authorAvatar
        ]);
        return $author->toArray();
    }

    /**
     * 解析内容中的图片
     * @param $content
     * @return array
     */
    private static function _parseContentImage($content): array
    {
        preg_match_all('/<img[^>]+src=[\'"]([^\'"]+)[\'"]/i', $content, $matches);
        $imageUrls = $matches[1];
        $imageList = [];
        $baseURL = env('COS_URL', '');
        foreach ($imageUrls as $url) {
            if (str_starts_with($url, $baseURL)) {
                $url = str_replace($baseURL, '', $url);
            }
            $imageList[] = $url;
        }
        return $imageList;
    }
}